package com.kris.oss;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;

public class OssGetApi {

	private static String endpoint = "http://oss.aliyuncs.com";
	private static String accessKeyId = "gvmMBtVhdrkVYqAt";
	private static String accessKeySecret = "BgDhEvnYqU1N3bawYc91Pgahm99umO";
	private static String bucketName = "itbour-static";

	private static OSS client = new OSSClientBuilder().build(endpoint,
			accessKeyId, accessKeySecret);// 饿汉单例

	public static OSS getInstance() {
		return client;
	}

	static final String content = "Hello OSS";
	static final String keyPrefix = "MyObjectKey";

	static ObjectListing objectListing = null;
	static String nextMarker = null;// 开始标记
	static final int maxKeys = 30;// 限制个数
	static List<OSSObjectSummary> sums = null;

	// 获取默认文件夹
	public static void getDefaultFile() {
		// use default parameter to list the files. By default up to 100 entries
		// could be listed.
		// 使用默认参数来列出文件。默认情况下，最多可以列出100个条目。
		System.out.println("Default paramters:");
		objectListing = client.listObjects(bucketName);
		sums = objectListing.getObjectSummaries();
		for (OSSObjectSummary s : sums) {
			System.out.println("\t" + s.getKey());
		}
	}

	// 获取数量限制文件夹
	public static void getLimitFile() {
		// Sets the max keys with 200 (the max value could be 1000).
		System.out.println("With max keys:");
		objectListing = client.listObjects(new ListObjectsRequest(bucketName)
				.withMaxKeys(2));

		sums = objectListing.getObjectSummaries();
		for (OSSObjectSummary s : sums) {
			System.out.println("\t" + s.getKey());
		}
	}

	// 获取带有指定前缀的对象。默认情况下，它返回到100个条目。
	public static void getAppointPrefix() {
		// Gets the object with specified prefix. By default it returns up to
		// 100 entries.
		System.out.println("With prefix:" + keyPrefix);
		objectListing = client.listObjects(new ListObjectsRequest(bucketName)
				.withPrefix(keyPrefix + "1"));

		sums = objectListing.getObjectSummaries();
		for (OSSObjectSummary s : sums) {
			System.out.println("\t" + s.getKey());
		}
	}

	public static void addNewFile() {// 添加文件夹
		// Prepare the environment---inserting 100 test files.
		List<String> keys = new ArrayList<String>();
		String key = "test/";
		InputStream instream = new ByteArrayInputStream(new byte[0]);// 新建文件夹
		client.putObject(bucketName, key, instream);
		keys.add(key);
		System.out.println("Put " + keys.size() + " objects completed.");
	}

	// 获取所有文件夹
	public static Map<String, Object> pageGetAllLimit(String nextMarker) {
		Map<String, Object> parm = new HashMap<String, Object>();
		try {
			System.out.println("nextMarker:" + nextMarker);
			objectListing = client.listObjects(new ListObjectsRequest(
					bucketName).withMarker(nextMarker).withMaxKeys(10));// 一页取10个文件夹

			sums = objectListing.getObjectSummaries();
			for (OSSObjectSummary s : sums) {
				System.out.println("\t" + s.getKey());
			}
			nextMarker = objectListing.getNextMarker();

			parm.put("sums", sums);
			parm.put("nextMarker", nextMarker);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			client.shutdown();
		}
		return parm;
	}

	// List all objects after marker
	public static void pageGetAllByPrefix() {
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(
				bucketName);

		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");

		// 列出fun目录下的所有文件和文件夹
		listObjectsRequest.setPrefix("liqi/");

		ObjectListing listing = client.listObjects(listObjectsRequest);

		// 遍历所有Object
		System.out.println("Objects:");
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			System.out.println(objectSummary.getKey());
		}

		// 遍历所有CommonPrefix
		System.out.println("\nCommonPrefixs:");
		for (String commonPrefix : listing.getCommonPrefixes()) {
			System.out.println(commonPrefix);
		}
	}

	// 删除指定文件
	public static void delAppointPrefix() {
//		List<String> keys = new ArrayList<String>();
//		keys.add("/miniprograms/203/images/docshare.jpg");
//		// Clean up the environment----deleting the test files.
//		DeleteObjectsResult deleteObjectsResult = client
//				.deleteObjects(new DeleteObjectsRequest(bucketName)
//						.withKeys(keys));
//		List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
//		for (String object : deletedObjects) {
//			System.out.println("\t" + object);
//		}
		
		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 删除文件。
		ossClient.deleteObject(bucketName, "miniprograms/203/images/docshare.jpg");
		// 关闭OSSClient。
		ossClient.shutdown();
	}

	public static void getWithPrefie(String nextMarker, String prefix,
			String dli) {
		ListObjectsRequest listObjectsRequest = null;
		listObjectsRequest = new ListObjectsRequest(bucketName)
				.withPrefix(prefix).withMarker(nextMarker).withMaxKeys(100)
				.withDelimiter("/");

		objectListing = client.listObjects(listObjectsRequest);

		sums = objectListing.getObjectSummaries();

		System.out.println(objectListing.getCommonPrefixes());// 当前文件夹下的文件夹
		for (String commonPrefix : objectListing.getCommonPrefixes()) {
			OSSObjectSummary o = new OSSObjectSummary();

			o.setBucketName(bucketName);
			o.setKey(subSt(prefix, commonPrefix));
			sums.add(o);
		}

		sums.remove(0);

		for (OSSObjectSummary s : sums) {
			System.out.println("\t" + s.getKey());
		}

		nextMarker = objectListing.getNextMarker();
		System.out.println(nextMarker);
	}

	public static String subSt(String pre, String comf) {
		if (pre != null) {
			int len = pre.length();
			return comf.substring(len);
		}
		return comf;
	}

	public static void uploadFile() throws IOException {
		// // Endpoint以杭州为例，其它Region请按实际情况填写。
		// String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
		// // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录
		// https://ram.console.aliyun.com 创建。
		// String accessKeyId = "<yourAccessKeyId>";
		// String accessKeySecret = "<yourAccessKeySecret>";
		// // 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,
				accessKeySecret);// 上传文件流。

		File file = new File("C:/Users/zhaojixing/Desktop/test.txt");
		InputStream inputStream = new FileInputStream(file);
		ossClient.putObject(bucketName, "liqi.txt", inputStream);

		// 关闭OSSClient。
		ossClient.shutdown();

	}

	public static void listOssFile() {
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(
				bucketName);

		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");

		// 列出fun目录下的所有文件和文件夹
		listObjectsRequest.setPrefix("liqi/");

		ObjectListing listing = client.listObjects(listObjectsRequest);

		// 遍历所有Object
		System.out.println("Objects:");
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			System.out.println(objectSummary.getKey());
		}

		// 遍历所有CommonPrefix
		System.out.println("\nCommonPrefixs:");
		for (String commonPrefix : listing.getCommonPrefixes()) {
			System.out.println(commonPrefix);
		}

	}

	public static void downFile() throws IOException {

		// bufferReader

		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,
				accessKeySecret);// 上传文件流。
		// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
		OSSObject ossObject = ossClient.getObject(bucketName, "liqi.txt");
		// 读取文件内容。
		InputStream input = ossObject.getObjectContent();
		byte[] buffBytes = new byte[1024];
		 
		 
		int read = 0;
		while ((read = input.read(buffBytes)) != -1) {
//		     outputStream.write(buffBytes, 0, read);
			System.out.println(buffBytes);
			
		}
		// 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
		// 关闭OSSClient。
		ossClient.shutdown();


	}

	// prefix 本次查询结果的前缀。
	public static void main(String[] args) throws IOException {
		// getDefaultFile();
		// getLimitFile();// 获取两个文件夹
		// getAppointPrefix();// 获取指定前缀下文件夹
		// addNewFile();
		// System.out.println(pageGetAllLimit("image/"));
		// pageGetAllByPrefix();
//		 getWithPrefie(null, "liqi/", "/");
		// addNewFile();
		 delAppointPrefix();
//		 uploadFile();
		// listOssFile();
		// File file = new File("C:/Users/zhaojixing/Desktop/test.txt");
		// InputStream inStream = new FileInputStream(file);
		// System.out.println(file.getName());
		// upload(accessKeyId, accessKeySecret, bucketName, endpoint, "",
		// file.getName(), inStream);

		// uploadFile();
//		downFile();

	}

}
